#!/usr/bin/env python

import csv

import pysam

from bam_counter.base_counter import BaseCounter
from bam_counter.positions_iterator import PositionsIterator, CharacterDelimitedPositionsReader

def bam_to_tsv(args):
    bam = pysam.Samfile(args.bam_file_name, 'rb')
    
    counter = BaseCounter(bam, args.min_base_qual, args.min_map_qual)
    
    writer = open(args.out_file_name, 'w')
    
    if args.positions_file is None:
        write_all_positions(counter, writer, args.min_depth)
    else:
        write_specified_positions(counter, writer, args.min_depth, args.positions_file, args.delimiter)
        
def write_all_positions(counter, writer, min_depth):
    for ref in sorted(counter.refs):
        for row in counter.iter_ref(ref):
            if row.depth >= min_depth:        
                writer.write(str(row))
                writer.write("\n")

def write_specified_positions(counter, writer, min_depth, positions_file, delimiter):
    if delimiter == 'tab':
        delimiter_char = '\t'
    elif delimiter == 'space':
        delimiter_char = ' '
    elif delimiter == 'comma':
        delimiter_char = ','
        
    positions_reader = CharacterDelimitedPositionsReader(positions_file, delimiter_char)
    
    positions_iter = PositionsIterator(counter, positions_reader)
    
    for row in positions_iter:
        if row.depth >= min_depth:
            writer.write(str(row))
            writer.write("\n")

if __name__ == "__main__":
    import argparse
    
    parser = argparse.ArgumentParser(prog='bam_to_tsv')
    
    parser.add_argument('bam_file_name', help='''BAM file.''')
    
    parser.add_argument('out_file_name',
                         help='Name of tsv file to be created.')
    
    parser.add_argument('--min_depth', default=1, type=int,
                         help='''Minimum depth of coverage in both tumour and normal sample required to use a site in
                         analysis. Default is 1.''')
    
    parser.add_argument('--min_base_qual', default=10, type=int,
                         help='''Remove bases with base quality lower than this. Default is 10.''')
    
    parser.add_argument('--min_map_qual', default=10, type=int,
                         help='''Remove bases with mapping quality lower than this. Default is 10.''')
    
    parser.add_argument('--positions_file', default=None,
                        help='''Path to list of positions to create tsv on. Should be tab separated chrom pos.''')
    
    parser.add_argument('--delimiter', choices=['tab', 'space', 'comma'], default='tab',
                        help='''Delimiter used to separate chrom and pos in positions file.''')
    
    parser.set_defaults(func=bam_to_tsv)
    
    args = parser.parse_args()

    args.func(args)
